﻿
Imports Sy.Data
Imports vb6 = Microsoft.VisualBasic

Public Class Frm_Main
    Private Sub Frm_Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
#Const GETAUS = 0
#If Not GETAUS = 0 Then
        aus.Add("End", False)
        aus.Add("nowUser", "当前用户：")
        aus.Add("Ver", " | 软件版本：")
        aus.Add("DataPath", "\Config\DB_2018110809.db")
        IO.File.WriteAllBytes(Application.StartupPath & "\" & Application.ProductName & ".aus", aus.AuthOutput)
        'End
#End If
        SetLayout(Me)
        Sy.SetHandle(My.Application)
        Sy.Update.CheckVersion()
        If Login(Reflection.Assembly.GetExecutingAssembly.GetName.Name, Application.ProductName) Then
            StateBar1.TextLeft = Aus("nowUser") & UserName '& aus("Ver") & Version
            DB = New SQLite(CKeyword.GetCreateSQL() &
                CFilterKeyword.GetCreateSQL() &
                CAreaInfo.GetCreateSQL() &
                Model_Map.GetCreateSQL() &
                CProductInfo.GetCreateSQL &
                C_Config_Map.GetCreateSQL, Application.StartupPath & "\Config\DB_2022110400.db")
            SqlObject.AddDB(DB)
            InitGlobalVariables(Me)
        End If
    End Sub

    Private Sub Btn_Process_Click(sender As Object, e As EventArgs) Handles Btn_Process.Click
        Dim button As Button = sender
        If button.Text = "开始" Then
            LstV_Task.Items.Clear()
            button.Text = "停止"
            '加载地区，过滤词
            '由于Load返回空会导致toList调用失败，Load接口现在已经改为必须返回Obj()
            '但是New List 直接覆盖 就没必要new了 这个要注意
            Dim areas = CAreaInfo.Load.ToList()
            Dim filterKeywords = CFilterKeyword.Load.ToList()
            Dim keywords = CKeyword.Load.ToList()
            Dim Filter As Filter
            If Rdb_None.Checked Then Filter = Filter.None
            If Rdb_Some.Checked Then Filter = Filter.Some
            If Rdb_Mobile.Checked Then Filter = Filter.Mobile
            Dim PageStart = 0
            Dim PageEnd = 2 '这里是定死两页嘛？
            Dim maps As New List(Of String)
            Dim checkItems As New List(Of MapMode)
            For Each emapitem As Sy.Enum.Item(Of MapMode) In CkListbox_FromMap.CheckedItems
                checkItems.Add(emapitem)
            Next
            LstV_Task.Enabled = False
            Sy.Threading.ThreadExecutor.Instance.Execute(
                Sub()
                    Dim mapProcess = New CMapProcess
                    For Each i In checkItems
                        Dim map = New Model_Map(i)
                        map.Add()
                        Dim curTask = New Model_Task(areas, keywords, filterKeywords, Filter, PageStart, PageEnd, map)
                        mapProcess.Process(curTask)
                    Next
                    Log("采集结束...")
                    Invoke(Sub()
                               button.Text = "开始"
                               LstV_Task.Enabled = True
                               Pager1.DoAdpterUI()
                           End Sub)
                End Sub, "采集数据", True)
        Else
            button.Text = "停止"
            button.Text = "开始"
            LstV_Task.Enabled = True
            Sy.Threading.ThreadExecutor.Instance.Abort()
            Pager1.DoAdpterUI()
        End If
    End Sub
    Private Sub CmbCity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbCity.SelectedIndexChanged
        Dim countries = GetThreeArea(CmbProvince.Text, CmbCity.Text)
        If countries.Length > 0 Then
            CmbCountry.Items.Clear()
            CmbCountry.Items.AddRange(countries)
            CmbCountry.SelectedIndex = 0
        End If
    End Sub

    Private Sub CmbProvince_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbProvince.SelectedIndexChanged
        Dim res = GetAreas(CmbProvince.Text)
        If Not CmbProvince.SelectedIndex = -1 Then CmbCountry.Visible = True
        If res IsNot Nothing Then
            CmbCity.Items.Clear()
            CmbCity.Items.AddRange(res)
            CmbCity.SelectedIndex = 0
            If res.Length = 1 Then
                CmbCity.Visible = False
            Else
                CmbCity.Visible = True
            End If
        End If
    End Sub

    Private Sub BtnAddArea_Click(sender As Object, e As EventArgs) Handles BtnAddArea.Click
        Dim area As String = ""
        If Not CmbProvince.Text.Length > 0 Then
            Sy.UI.Form.MsgBox.Show("省市选项不能为空", "确认")
            Exit Sub
        End If
        If CmbCity.Visible = True Then
            area &= CmbProvince.Text & "_" & CmbCity.Text & "_" & CmbCountry.Text
        Else
            area &= CmbProvince.Text & "_" & CmbCountry.Text
        End If
        Dim areaInfo As New CAreaInfo(area)
        areaInfo.Add()
        List_Area.Items.Add(areaInfo)
    End Sub

    Private Sub BtnClearArea_Click(sender As Object, e As EventArgs) Handles BtnClearArea.Click
        CAreaInfo.DelAll()
        List_Area.Items.Clear()
    End Sub

    Private Sub BtnClearKeywords_Click(sender As Object, e As EventArgs) Handles BtnClearKeywords.Click
        CKeyword.DelAll()
        List_Keywords.Items.Clear()
    End Sub

    Private Sub BtnClearFilterKeywords_Click(sender As Object, e As EventArgs) Handles BtnClearFilterKeywords.Click
        CFilterKeyword.DelAll()
        List_Filter_Keywords.Items.Clear()
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles BtnDelArea.Click
        If List_Area.SelectedItems.Count > 0 Then
            For i = List_Area.SelectedItems.Count - 1 To 0 Step -1
                Dim item As CAreaInfo = List_Area.SelectedItems(i)
                List_Area.Items.Remove(item)
                item.Del()
            Next
        Else
            Sy.UI.Form.MsgBox.Show("请选中要删除项", "确定")
        End If
    End Sub

    Private Sub BtnDelKeywords_Click(sender As Object, e As EventArgs) Handles BtnDelKeywords.Click
        Dim i As CKeyword = List_Keywords.SelectedItem
        If i Is Nothing Then
            Sy.UI.Form.MsgBox.Show("请选中要删除项", "确定")
        Else
            List_Keywords.Items.Remove(i)
            i.Del()
        End If
    End Sub

    Private Sub BtnDelFilterKeywords_Click(sender As Object, e As EventArgs) Handles BtnDelFilterKeywords.Click
        If List_Filter_Keywords.SelectedItems.Count > 0 Then
            For i = List_Filter_Keywords.SelectedItems.Count - 1 To 0 Step -1
                Dim item As CFilterKeyword = List_Filter_Keywords.SelectedItems(i)
                List_Filter_Keywords.Items.Remove(item)
                item.Del()
            Next
        Else
            Sy.UI.Form.MsgBox.Show("请选中要删除项", "确定")
        End If
    End Sub

    Private Sub BtnAddKeyword_Click(sender As Object, e As EventArgs) Handles BtnAddKeyword.Click
        If TxtKeywords.Text.Trim.Length > 0 Then
            Dim mk As New CKeyword(TxtKeywords.Text)
            mk.Add()
            List_Keywords.Items.Add(mk)
            TxtKeywords.Clear()
        Else
            Sy.UI.Form.MsgBox.Show("关键词不能为空", "确定")
        End If
    End Sub

    Private Sub BtnAddFilterKeyword_Click(sender As Object, e As EventArgs) Handles BtnAddFilterKeyword.Click
        If TxtFilterKeywords.Text.Trim.Length > 0 Then
            Dim Cf As New CFilterKeyword(TxtFilterKeywords.Text)
            Cf.Add()
            List_Filter_Keywords.Items.Add(Cf)
            TxtFilterKeywords.Clear()
        Else
            Sy.UI.Form.MsgBox.Show("过滤关键词不能为空", "确定")
        End If
    End Sub

    Private Sub BtnTaskClearAll_Click(sender As Object, e As EventArgs) Handles BtnTaskClearAll.Click
        Sy.UI.Form.MsgBox.Show("确定清空全部数据吗?",
                               {"清空", "取消"},
                               "提示",
                               Me,
                               {Sub()
                                    CProductInfo.DelAll()
                                    Log("清空数据完成")
                                    Pager1.DoAdpterUI()
                                End Sub,
                                Sub() Log("取消清空")})
    End Sub

    Private Sub BtnTaskClearSelect_Click(sender As Object, e As EventArgs) Handles BtnTaskClearSelect.Click
        Sy.UI.Form.MsgBox.Show("确定删除选中任务吗?",
                    {"删除", "取消"},
                    "提示",
                    Me,
                    {Sub()
                         Dim tasks As New List(Of CProductInfo)
                         For i = 0 To LstV_Task.CheckedItems.Count - 1
                             tasks.Add(LstV_Task.CheckedItems(i).Tag)
                         Next
                         CProductInfo.Del(tasks.ToArray)
                         Log("删除数据完成")
                         Pager1.DoAdpterUI()
                     End Sub,
                     Sub() Log("取消删除")})
    End Sub

    Private Sub Ckb_IsAll_CheckedChanged(sender As Object, e As EventArgs) Handles Ckb_IsAll.CheckedChanged
        For i = 0 To LstV_Task.Items.Count - 1
            LstV_Task.Items(i).Checked = sender.Checked
        Next
    End Sub

    Private Sub Pager1_AdapterUI(sender As Object, e As Sy.UI.AdapterUIEventArgs) Handles Pager1.AdapterUI
        LstV_Task.Clear()
        Sy.UI.Common.UIAdapter.ListviewAdapter(Of CProductInfo)(_Frm_Main.LstV_Task, "编号")
        e.TotalCount = CProductInfo.GetRecordCount()
        Debug.Print(e.limitSQL)
        Dim I As Integer = e.offset + 1
        Dim sqlc = New SqlCondition With {
            .OrderBy = New OrderByCondition(DefalutSort, OrderByCondition.SequenceMode.ASC),
            .Limit = New LimitCondition(e.limitSQL)
        }
        For Each item As Object In CProductInfo.Load(sqlc)
            Dim itm = LstV_Task.Items.Add(Sy.UI.Common.UIAdapter.GetListViewItem(item, I)) '状态 进度 id
            itm.Tag = item
            I += 1
        Next
        Ckb_IsAll.Checked = False
    End Sub

    Private Sub CkListbox_FromMap_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CkListbox_FromMap.ItemCheck
        'MsgBox(Sy.Data.JsonObject.Serialize(sender))
        If Inited Then
            Dim item As Sy.Enum.Item(Of MapMode) = CkListbox_FromMap.Items(e.Index)
            Dim Checked = Not (e.CurrentValue = CheckState.Checked)
            If C_Config_Map.Instance.ChecksDic.ContainsKey(item.GetDescription) Then
                C_Config_Map.Instance.ChecksDic(item.GetDescription) = Checked
            Else
                C_Config_Map.Instance.ChecksDic.Add(item.GetDescription, Checked)
            End If
            C_Config_Map.Instance.Edt()
        End If
    End Sub
    Private Sub BtnToExcel_Click(sender As Object, e As EventArgs) Handles BtnToExcel.Click
        '保存文件的名称
        Dim saveDlg = New SaveFileDialog With {
            .Title = "保存文件",
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
            .FileName = Date.Now.ToString("yyyyMMddHHmm"),
            .Filter = "Excel 文件|*.xls|csv|*.csv",
            .RestoreDirectory = True
        }
        Debug.Print(saveDlg.FileName.ToString)
        Dim saveName As String = ""
        If saveDlg.ShowDialog = DialogResult.OK Then
            saveName = saveDlg.FileName
            Dim dt As DataTable
            If CkbExportOnlyPhone.Checked Then
                dt = CProductInfo.GetMobileDataTable()
            Else
                '获取导出选项
                dt = CProductInfo.GetDataTable
            End If
            Try
                'UtilsHelper.listViewToDataTable(LstV_Task, dt)
                CExcelProcess.DataTableToExcel(dt, saveName)
                Sy.UI.Form.MsgBox.Show("表格导出完成", "确定")
            Catch ex As Exception
                Sy.UI.Form.MsgBox.Show("表格导出失败", "确定")
            End Try
        End If
    End Sub
    Private Sub BtnToTxt_Click(sender As Object, e As EventArgs) Handles BtnToTxt.Click
        '保存文件的名称
        Dim saveDlg = New SaveFileDialog With {
            .Title = "保存文件",
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
            .FileName = Date.Now.ToString("yyyyMMddHHmm"),
            .Filter = "文本 文件|*.txt",
            .RestoreDirectory = True
        }
        Dim saveName As String = ""
        If saveDlg.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            saveName = saveDlg.FileName
        End If
        If Not saveName.Length > 0 Then Exit Sub
        Dim dt As DataTable
        If CkbExportOnlyPhone.Checked Then
            dt = CProductInfo.GetMobileDataTable()
        Else
            '获取导出选项
            dt = CProductInfo.GetDataTable
        End If
        Try
            'UtilsHelper.listViewToDataTable(LstV_Task, dt)
            UtilsHelper.DataTableToTxt(dt, saveName)
            Sy.UI.Form.MsgBox.Show("文本导出完成", "确定")
        Catch ex As Exception
            Sy.UI.Form.MsgBox.Show("文本导出失败", "确定")
        End Try
    End Sub
    Private Sub BtnToCsv_Click(sender As Object, e As EventArgs) Handles BtnToCsv.Click
        '保存文件的名称
        Dim saveDlg = New SaveFileDialog With {
            .Title = "保存文件",
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
            .FileName = Date.Now.ToString("yyyyMMddHHmm"),
            .Filter = "CSV 文件|*.csv",
            .RestoreDirectory = True
        }
        Dim saveName As String = ""
        If saveDlg.ShowDialog = DialogResult.OK Then
            saveName = saveDlg.FileName
        End If
        If Not saveName.Length > 0 Then Exit Sub
        '获取导出选项
        Dim dt = CProductInfo.GetDataTable
        Try
            'UtilsHelper.listViewToDataTable(LstV_Task, dt)
            UtilsHelper.DataTableToCSV(dt, saveName)
            Sy.UI.Form.MsgBox.Show("CSV导出完成", "确定")
        Catch ex As Exception
            Sy.UI.Form.MsgBox.Show("CSV导出失败", "确定")
        End Try
    End Sub
    Private Sub BtnToVCF_Click(sender As Object, e As EventArgs) Handles BtnToVCF.Click
        '保存文件的名称
        Dim saveDlg = New SaveFileDialog With {
            .Title = "保存文件",
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
            .FileName = Date.Now.ToString("yyyyMMddHHmm"),
            .Filter = "VCF 文件|*.VCF",
            .RestoreDirectory = True
        }
        If saveDlg.ShowDialog = DialogResult.OK Then
            Dim saveName As String = saveDlg.FileName
            Dim v As New File.Cls_VCF
            '获取导出选项
            For Each m In CProductInfo.Load()
                Dim Name = m.Title
                Dim Tel = If(m.mobile.IsNotWhiteSpace(), m.mobile, m.Phone)
                If Tel.Length > 0 Then
                    v.Add(Name, Tel)
                End If
            Next
            Try
                IO.File.WriteAllBytes(saveName, v.GetByte)
                Sy.UI.Form.MsgBox.Show("CSV导出完成", "确定")
            Catch ex As Exception
                Sy.UI.Form.MsgBox.Show("CSV导出失败", "确定")
            End Try
        End If
    End Sub
    Private DefalutSort As CProductInfo.SQLkey = CProductInfo.SQLkey.Address
    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Gp_Sort.Visible = True
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Gp_Sort.Visible = False
        Pager1.DoAdpterUI()
    End Sub

    Private Sub Rb_Location_CheckedChanged(sender As Object, e As EventArgs) Handles Rb_Workplane.CheckedChanged
        DefalutSort = CProductInfo.SQLkey.Workplane
    End Sub

    Private Sub Rb_Address_CheckedChanged(sender As Object, e As EventArgs) Handles Rb_Address.CheckedChanged
        DefalutSort = CProductInfo.SQLkey.Address
    End Sub

    Private Sub Rb_Mobile_CheckedChanged(sender As Object, e As EventArgs) Handles Rb_Mobile.CheckedChanged
        DefalutSort = CProductInfo.SQLkey.mobile
    End Sub
End Class
